//
//  CNEmoticonModel.swift
//  EmoticonKeyboard
//
//  Created by 陈锦聪 on 16/4/1.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit

class CNEmoticonModel: NSObject, NSCoding {

    /// 网络传输的表情名称
    var chs: String?
    /// 客户端显示的表情名称
    var png: String? {
        didSet {
            pngPath = bundlePath + "/" + id + "/" + png!
        }
    }
    /// png完整路径
    var pngPath: String?
    /// 16进制emoji表情
    var code: String? {
        didSet {
            // 将 code 转成 emoji字符串
            let scanner = NSScanner(string: code!)
            var result: UInt32 = 0
            scanner.scanHexInt(&result)
            emoji = "\(Character(UnicodeScalar(result)))"
        }
    }
    /// emoji字符串
    var emoji: String?
    /// 表情包文件夹
    var id: String
    
    init(dict: [String: String], id: String) {
        self.id = id
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    override var description: String {
        return "\n\tEmoticonModel: [chs: \(chs), png: \(png), code: \(code)]"
    }
    /// 将表情模型转成属性文本
    func emoticonModelToAttributedString(font: UIFont) -> NSAttributedString {
        let attachment = CNTextAttachment()
        attachment.image = UIImage(named: pngPath!)
        attachment.chs = chs
        let wh = font.lineHeight ?? 14
        // bounds和frame的x,y坐标相反
        attachment.bounds = CGRect(x: 0, y: -4, width: wh, height: wh)
        let attrString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        attrString.addAttributes([NSFontAttributeName: font], range: NSRange(location: 0, length: 1))
        return attrString
    }
    /// 根据表情名称查找表情模型
    class func emoticonNameToEmoticonModel(name: String) -> CNEmoticonModel? {
        for package in CNEmoticonManager.sharedInstance.packages {
            for emoticon in package.emoticons {
                if emoticon.chs == name {
                    return emoticon
                }
            }
        }
        return nil
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(chs, forKey: "chs")
        aCoder.encodeObject(png, forKey: "png")
        aCoder.encodeObject(code, forKey: "code")
        aCoder.encodeObject(emoji, forKey: "emoji")
        aCoder.encodeObject(id, forKey: "id")
    }
    required init?(coder aDecoder: NSCoder) {
        chs = aDecoder.decodeObjectForKey("chs") as? String
        png = aDecoder.decodeObjectForKey("png") as? String
        code = aDecoder.decodeObjectForKey("code") as? String
        emoji = aDecoder.decodeObjectForKey("emoji") as? String
        // id的类型为String,解档之后不能为空
        id = aDecoder.decodeObjectForKey("id") as? String ?? ""
        if let png = png {
            pngPath = bundlePath + "/" + id + "/" + png
        }
    }
    
}
